package Gui;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

import Searcher.SearchResults;
import Searcher.TestSearcher;
import Utils.EditDistance;
import Utils.ResultDisplayUtility;
import Utils.RolloverButton;
import Utils.VerseInfoEncoder;

/**
 * Events are handled directly by this class since it implements ActionListener 
 * see the bottom for event handling
 * @author ale 
 *
 */
public class TestGui implements ActionListener, HyperlinkListener, KeyListener{
	private final static String relativePath = System.getProperty("user.dir");
	private static final int RESULTS_BEFORE = 10;
	private static final int RESULTS_AFTER = 19;

	private static final int MAX_SUGGESTIONS = 20;
	private static final int DEFAULT_SUGGPANEL_WIDTH = 20;
	private static final String CHECKBOX_ON_LINK_INNER = "<img src=\"file://"+relativePath+"/images/cbxon.png\" border=\"0\">";
	private static final String CHECKBOX_OFF_LINK_INNER = "<img src=\"file://"+relativePath+"/images/cbxoff.png\" border=\"0\">";
	private static final String PREV_BUTTON_LINK_INNER = "<img src=\"file://"+relativePath+"/images/prev.png\" border=\"0\">";
	private static final String NEXT_BUTTON_LINK_INNER = "<img src=\"file://"+relativePath+"/images/next.png\" border=\"0\">";
	private static final String QUERY_HELP = "Allowed words: AND, OR, NOT, [chars]*[optional:chars]";
	private int OFFSET = 0;

	private final int QUERY_WIDTH = 40; //expressed in columns

	private final String SEPARATOR = "%%";	//used to separate <corrected_word>||<mispelled_word>, for event handling

	private JPanel searchPanel;
	private RolloverButton querySearchButton;
	private JEditorPane editorPane;
	private JLabel statusLabel;
	private JLabel display;
	private JLabel results;
	private JTextField queryText;
	private JLabel suggestion;
	private JPanel suggestionPanel;
	private JComboBox numberOfRes;
	private JFrame window;

	private VerseInfoEncoder verseInfoEncoder;			//used to form and decode links urls (after search)
	private ResultDisplayUtility resultDisplayUtility; 	//to parse displayed text (to present in a nice way)
	private JTabbedPane tabbedPane;
	private JPanel resultsPanel;
	private JEditorPane resultsEditorPane;
	private JScrollPane scrollPane;
	private JButton saveHistoryButton;
	private String filepath = "";
	private JButton loadHistoryButton;
	private JButton clearHistoryButton;
	private JFileChooser filechooser = new JFileChooser();


	private JPanel historyPanel;
	private JEditorPane historyEditorPane;

	int[] howMany = {10, 20, 50, 100};
	String[] howmany2;
	boolean[] relevanceFeedback;

	public ArrayList<String> historyQuery = new ArrayList<String>();
	private ArrayList<String[]> topScoredOfCurrentResults;


	public TestGui() {
		verseInfoEncoder = new VerseInfoEncoder();
		resultDisplayUtility = new ResultDisplayUtility();
	}


	public  void ConstructGui() {
		System.out.println(relativePath);
		//window:
		window = new JFrame("Religion finder");

		//tabbed pane
		tabbedPane = new JTabbedPane();
		window.add(tabbedPane);

		//search panel: -----------------------------------------
		LayoutManager mainPanelLayout = new BorderLayout();
		searchPanel = new JPanel(mainPanelLayout);

		// QUERY SPACE ---------------------------------------------------
		//JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		PanelWithBackground queryPanel = new PanelWithBackground("images/grid2.png");
		queryPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
		
		//Bejar:
		JLabel jl = new JLabel(new ImageIcon("images/bejar.jpg"));
		queryPanel.add(jl);

		//queryText:
		queryText = new JTextField(QUERY_WIDTH);
		queryText.addKeyListener(this);
		//querySearchButton = new JButton("Search");
		querySearchButton = new RolloverButton("", "search_off.png", "search_on.png");
		querySearchButton.setBorderPainted(true);
		queryPanel.add(queryText);
		//querySearchButton:
		querySearchButton.addActionListener(this);
		queryPanel.add(querySearchButton);
		display = new JLabel("Display");
		results = new JLabel("results per page");
		display.setForeground(Color.BLACK); //FUCK
		//display.setFont(new Font("Verdana", Font.BOLD, 12));
		results.setForeground(Color.BLACK);
		queryPanel.add(display);


		builarray();
		numberOfRes = new JComboBox(howmany2);
		numberOfRes.addKeyListener(this);
		queryPanel.add(numberOfRes);	
		queryPanel.add(results);

		searchPanel.add(queryPanel, BorderLayout.NORTH);

		// end QUERY SPACE -----------------------------------------------

		//suggestions panel
		suggestionPanel = new JPanel(new GridLayout(MAX_SUGGESTIONS, 1));
		suggestion = new JLabel("Did you mean:");
		suggestionPanel.add(suggestion);
		searchPanel.add(suggestionPanel, BorderLayout.WEST);

		//editor
		editorPane = new JEditorPane();
//		try {	//try to load the 'welcome' page
//		URL u = new URL(startTextUrl);
//		//editorPane = new JEditorPane(u);
//		editorPane = new JEditorPane("text/html", startTextUrl);
//		} catch (IOException e) {
//		editorPane.setText("Error downloading latest news. No internet connection?");
//		e.printStackTrace();
//		}

		//scroll
		scrollPane = new JScrollPane(editorPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		searchPanel.add(scrollPane, BorderLayout.CENTER);
		editorPane.setContentType("text/html");

//		if(JOptionPane.showConfirmDialog(window,
//		"Do you want to check out the news? Ehhh?",
//		"News",
//		JOptionPane.YES_NO_OPTION,
//		JOptionPane.QUESTION_MESSAGE,
//		null) == JOptionPane.NO_OPTION) 
//		//put sample text in it (if user wants) -- choose no to load sample <v>...</v>
//		editorPane.setText(text); 

		//editor configuration
		Font f = new Font( "Andalus", Font.BOLD + Font.ITALIC, 12 );
		editorPane.setFont(f);
		editorPane.addHyperlinkListener(this);
		editorPane.setEditable(false);

		//COPY button:
		JPanel righPanel = new JPanel(new GridLayout(20, 1));
		searchPanel.add(righPanel, BorderLayout.EAST);

		//Relevance FB button:
		String rfbButtonTooltip = "Select a number of verses from the results of the search.\nThen click here to perform a new search finding documents relevant so the same subject.";

		//results panel: -----------------------------------------
		resultsPanel = new JPanel(new BorderLayout());
		resultsEditorPane = new JEditorPane();
		///	resultsEditorPane.setContentType("text/html"); // !!
		resultsEditorPane.setContentType("text/html"); // !!
		JScrollPane resScrollPane = new JScrollPane(resultsEditorPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		resultsPanel.add(resScrollPane, BorderLayout.CENTER);

		//history panel:
		JPanel historyRightPanel = new JPanel(new GridLayout(20,1));
		historyPanel = new JPanel(new BorderLayout());
		historyEditorPane = new JEditorPane();
		historyEditorPane.setContentType("text/html");
		historyEditorPane.addHyperlinkListener(this);
		historyEditorPane.setEditable(false);

		JScrollPane historyScrollPane = new JScrollPane(historyEditorPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		historyPanel.add(historyScrollPane, BorderLayout.CENTER);

		saveHistoryButton = new JButton("Save History");
		saveHistoryButton.addActionListener(this);
		loadHistoryButton = new JButton("Load History file");
		loadHistoryButton.addActionListener(this);
		clearHistoryButton = new JButton("Clear History");
		clearHistoryButton.addActionListener(this);

		historyRightPanel.add(saveHistoryButton);
		historyRightPanel.add(loadHistoryButton);
		historyRightPanel.add(clearHistoryButton);
		historyPanel.add(historyRightPanel, BorderLayout.EAST);

		//   ----------------------------------------------------- (common parts)

		//status bar (for information such as number of hits and elapsed time):
		statusLabel = new JLabel("Ready");
		window.add(statusLabel, BorderLayout.SOUTH);

		//end
		tabbedPane.addTab("Search", searchPanel); //add the tabs ["search"]["results"]...
		tabbedPane.addTab("Results", resultsPanel);
		tabbedPane.addTab("History", historyPanel);

		window.setVisible(true);
		window.pack();
		window.setBounds(0, 0, 1024, 768);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//leave space left to the editorPanel:
		resetSuggestionPanel();

		//focus to queryText:
		queryPanel.requestFocusInWindow();
		queryText.requestFocusInWindow();

		
	}//end constructGui()


	/**
	 * Used for hits_per_page: it copies the 'howMany' array (of int) into
	 * the array 'howMany2' which is of types String
	 */
	public void builarray() {
		howmany2 = new String[howMany.length];
		for (int i = 0; i < howMany.length; i++) {
			howmany2[i] = new Integer(howMany[i]).toString();
		}
	}


	/**
	 * Sets a new text into the status bar
	 * @param newStatus
	 */
	public void setStatus(String newStatus) {
		statusLabel.setText(newStatus);
	}


	/**
	 * True if queryText area is focused and the key pressed (generating the event) 
	 * is the RETURN key
	 */
	//pressed 'enter' in search query space?
	private boolean wantToSearch(KeyEvent e) {
		return (queryText.hasFocus() && e.getKeyCode() ==KeyEvent.VK_ENTER);
	}

	/**
	 * The action handler
	 */


	//ACTION LISTENER PART:
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == saveHistoryButton) {
			createHistoryFile();
			setStatus("SAVED TO" + filepath);
			//TODO
		} else if (e.getSource() == loadHistoryButton) {
			loadHistoryFile();
			//TODO
		} else if (e.getSource() == clearHistoryButton) {
			clearHistory();
			//TODO
		} else if (e.getSource() == querySearchButton) {
			OFFSET = 0;
			queryText.setText(relevanceFeebback());
			performQuery();
		} else if (e.getActionCommand() != "") {								// (*) the action has an actioncommand (use to perform new query)
			String correctingCommand = e.getActionCommand();
			System.out.println("ACTION: " + correctingCommand);
			correctFromCommand(correctingCommand);
		}
	}

	private String relevanceFeebback() {
		ArrayList<String> wordsForNewQuery = new ArrayList<String>();
		String[] queryWords = queryText.getText().split(" ");

		//not unique words from the query
		for(String qw : queryWords)
			wordsForNewQuery.add(qw);

		//not unique words from top scoreds
		for (int i = 0 ; i < relevanceFeedback.length ; i++) { 
			if (relevanceFeedback[i]) 
				for (String tsw : topScoredOfCurrentResults.get(i))
					wordsForNewQuery.add(tsw);
		}

		for(String s : wordsForNewQuery)
			System.out.print(s+"|");
		System.out.println("|");

		//remove duplicates:
		String newQueryNoDupToString = removeDuplicatesToString(wordsForNewQuery);

		queryText.setText(newQueryNoDupToString);
		return newQueryNoDupToString;
	}

	/**
	 * Takes an ArrayList<String> and removes its duplicates ignorig the case. Then it's
	 * sent to String separing each term with " " (space). The null are removed.
	 * @param arrayList
	 * @return
	 */
	private String removeDuplicatesToString(ArrayList<String> arrayList) {
		ArrayList<String> arrayList2 = new ArrayList<String>();
		for(int i = 0 ; i < arrayList.size() ; i++) 
			if(!containsIgnoreCase(arrayList2, arrayList.get(i)) && arrayList.get(i) != null)
				arrayList2.add(arrayList.get(i));
		String out = "";
		for(int i = 0 ; i < arrayList2.size() ; i++) {
			String s = arrayList2.get(i);
			out += s;
			if(i < arrayList2.size()-1)
				out += " ";
		}
		return out;
	}

	/**
	 * Returns true if the array contains the string ignoring the case. To do this, 
	 * in the comparison, both strings are made .toLowerCase()
	 * @param array
	 * @param string
	 * @return
	 */
	private boolean containsIgnoreCase(ArrayList<String> array, String string) {
		System.err.println("size: "+array.size());
		for(String s : array) {
			if (s.toLowerCase().equals(string.toLowerCase()))
				return true;
		}
		return false;
	}


	private void correctFromCommand(String correctingCommand) {
		String[] wordsPair = new String(correctingCommand).split(SEPARATOR);						//contains corrected||mispelled
		System.out.println(wordsPair.length);
		String corrected = wordsPair[0];
		String mispelled = wordsPair[1];
		System.out.println(mispelled + " --> " + corrected);
		String correctedQuery = queryText.getText().replaceAll(mispelled, corrected);		
		queryText.setText(correctedQuery);
		performQuery();
	}

	private void resetSuggestionPanel(){
		suggestionPanel.removeAll();
		suggestionPanel.setPreferredSize(new Dimension(DEFAULT_SUGGPANEL_WIDTH, 0));
		suggestionPanel.updateUI();
	}

//	int historyCounter = 0;



	private void displayHistory(ArrayList<String> array) {
		String his = "<table>";
		for (int i = 0; i < array.size(); i++) {
			String query = array.get(i).split(SEPARATOR)[0];
			String date = array.get(i).split(SEPARATOR)[1];
			String finDate = date.replace("CET", "");
			his += "<font face=\"Verdana\">" + "<tr>" + "<td>" + "<i>" + finDate + "</i>" + "</td>" + 
			"<td>" + "<b>" + "<a href=\"HIS" + query + "\">"+query+"</a>" + "</b>" + 
			"</td>" + "</tr>" + "</font>";
//			System.out.println("LINK:"+ linkQuery);
		}
		his += "</table>";
		historyEditorPane.setText(his);				
	}

	private void clearHistory() {
		historyQuery.clear();
		historyEditorPane.setText("");
	}



	/**
	 * Saves the query history to a file
	 */
	private void createHistoryFile(){
		filechooser.showSaveDialog(window);
		File toSave = filechooser.getSelectedFile();
		filepath = toSave.getAbsolutePath();

		FileWriter file = null;
		try {
			file = new FileWriter(toSave);
			BufferedWriter out = new BufferedWriter (file);
			for (int i = 0; i < historyQuery.size(); i++) {
				out.write(historyQuery.get(i) + "\n");
			}
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Load a history file
	 */
	private void loadHistoryFile(){
		historyQuery.clear();
		String line;
		filechooser.showOpenDialog(window);
		File file = filechooser.getSelectedFile();

		try {
			BufferedReader in = new BufferedReader(new FileReader(file));

			try {
				while ((line = in.readLine()) != null) {
					historyQuery.add(line);
					System.out.println(line + "\n");
				}
				displayHistory(historyQuery);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void resetSearchResultsPane() {
		editorPane.setText("");
	}


	private String addResButtons() {
		String out = "";

		out += "<br><br><center>";
		out += "<table><tr>";
		if (prev)
			out += "<td><a href=\"PREV\">"+PREV_BUTTON_LINK_INNER+"</a></td>";
		System.out.println("<td><a href=\"PREV\"><img src=\""+relativePath+"/images/prev.png\"></a></td>");
		out += "<td><a href=\"FEEDBACK\">RELEVANCE FEEDBACK</a></td>";
		out += "<td><a href=\"NEXT\">"+NEXT_BUTTON_LINK_INNER+"</a></td>";
		out += "</table></tr>";
		out += "</center>";

//		System.out.println(new File(relativePath+"/images/prev.png").exists());
//		out += "<a href=\"PREV\"><img src=\""+relativePath+"/images/prev.png\"></a>";
//		System.out.println("<a href=\"PREV\"><img src=\""+relativePath+"/images/prev.png\"></a>");

		return out;

	}


	//do the search of a query
	private void performQuery() {
		removeDupSpaces();
		String text = queryText.getText();
		resetSuggestionPanel();
		if (text.equals("") || text.equals(" ")){
			setStatus("");
			resetSearchResultsPane();
			return;
		}

		int hitsperpage = howMany[numberOfRes.getSelectedIndex()];
		TestSearcher test = new TestSearcher("index/", hitsperpage);
		Date start = new Date();
		SearchResults searchResults = null;
		try {
			searchResults = test.search(text, "verseContents", "bktLong", hitsperpage, OFFSET);
		} catch (Exception e) {
			System.err.println(e.getClass());
			resetSuggestionPanel();
			resetSearchResultsPane();
			editorPane.setText("<b>Query error</b><br>" + QUERY_HELP);
			setStatus("Query error");
			return;
		}

		String[] results = null;
		if (searchResults != null)
			results = searchResults.getDisplayResults();
		Date end = new Date();
		String allResultsString = "<font face=\"Verdana\">";


		if (searchResults != null) {
			allResultsString = addResButtons();
			setStatus((searchResults.getMatches()) + " results found in " + (end.getTime()-start.getTime())+"ms");	//search duration
			relevanceFeedback = new boolean[results.length];

			//allResultsString += new Integer(searchResults.getMatches()).toString() + " total matching documents<br>"; //now it's in status bar
			topScoredOfCurrentResults = new ArrayList<String[]>();
			for (int i = 0; i < results.length; i++) {
				allResultsString += results[i];
				topScoredOfCurrentResults.add(searchResults.getTopScoredArray(i));
				//allResultsString += searchResults.topScoredWordsToString(i) + "<br>";	 //prints the topScored words for the prev. verse
				allResultsString += "<a href='RF"+i+"'> "+idToRelLink(i, relevanceFeedback[i])+"</a>";
				allResultsString += "Relevant<br><br>";
				System.out.println("<a href='RF"+i+"'> "+idToRelLink(i, relevanceFeedback[i])+"</a><br><br>");
			}
			allResultsString += addResButtons();
		} 
		// words highlight
		editorPane.setText(allResultsString + "</font>");
		//scroll (to top)
		scroll(editorPane, TOP);
		editorPane.updateUI();
		if (results == null) {
			setStatus("no" + " results found  (search lasted " + (end.getTime()-start.getTime())+" ms)");	//search duration
			suggestionPanel.setPreferredSize(null);
			System.out.println("no results");
			ArrayList<ArrayList<String>> sugg;
			EditDistance ed = new EditDistance();
			sugg = ed.getSimilarResults(queryText.getText().split(" "));
			String[] queryWords = queryText.getText().split(" ");
			suggestionPanel.add(suggestion);
			for (int j = 0 ; j < sugg.size() ; j++) {
				for (int i = 0; i < sugg.get(j).size(); i++) {
					JButton sugButton = new JButton(sugg.get(j).get(i));
					//actionListener on sugButton
					sugButton.addActionListener(this);
					sugButton.setBorderPainted(false);
					sugButton.setFont(new Font("verdana", Font.BOLD, 12));
					sugButton.setForeground(Color.BLUE);
					sugButton.setSize(sugButton.getMinimumSize());
					String actionCommand = sugg.get(j).get(i) + SEPARATOR + queryWords[j];	// put: corrected_word||mispelled_word
					sugButton.setActionCommand(actionCommand);					// into actioncommand of the button (*)
					suggestionPanel.add(sugButton);
					sugButton.updateUI();
					editorPane.setText(editorPane.getText() + "\n" + sugg.get(j).get(i));
					System.out.println("> "+sugg.get(j).get(i));
				}
			}
			suggestionPanel.updateUI();				
		} else {
			String date = new Date (System.currentTimeMillis()).toString();
			historyQuery.add(text + SEPARATOR + date);
			displayHistory(historyQuery);
		}
	}


	private void removeDupSpaces() {
		String query = queryText.getText();
		query = query.replaceAll("(\\ \\ )(\\ )*", " ");
		queryText.setText(query);
	}


	/**
	 * This is used for relevance feedback: it generates the inner part of a link
	 * that should be a ckeckbox.
	 * @param id
	 * @param checked
	 * @return
	 */
	private String idToRelLink(int id, boolean checked) {
		String innerHtml;
		if (checked)
			innerHtml = CHECKBOX_ON_LINK_INNER;
		else innerHtml = CHECKBOX_OFF_LINK_INNER;
		return "<a"+id+">"+innerHtml+"</a"+id+">";
	}

	boolean prev = false;

	/**
	 * fired when clicked a link from editorpane
	 */
	public void hyperlinkUpdate(HyperlinkEvent e) {
		if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			if (e.getDescription().startsWith("REL")) {
				String newquery = queryText.getText() + e.getDescription().replace("REL"," ");
				queryText.setText(newquery);
				OFFSET = 0;
				performQuery();
			} else if (e.getDescription().startsWith("HIS")) {
				String link = e.getDescription().replaceFirst("HIS","");
				OFFSET = 0;
				queryText.setText(link);
				tabbedPane.setSelectedComponent(searchPanel);
				performQuery();
			} else if (e.getDescription().startsWith("NEXT")) {
				System.out.println("PREV");
				OFFSET++;
				performQuery();
				prev = true;
			} else if ((e.getDescription().startsWith("PREV")) && prev) {
				OFFSET--;
				performQuery();
				if (OFFSET == 0) {
					prev = false;}
			} else if (e.getDescription().startsWith("FEEDBACK")) {	
				queryText.setText(relevanceFeebback());
				performQuery();
			} else if (e.getDescription().startsWith("RF")) {
				String command = e.getDescription().replaceFirst("RF", "");
				int resultID = new Integer(command).intValue();
				String oldCheckbox = idToRelLink(resultID, relevanceFeedback[resultID]);
				String newCheckbox = idToRelLink(resultID, !relevanceFeedback[resultID]);

				@SuppressWarnings("unused")String chbx = "";
				if(relevanceFeedback[resultID])
					chbx = CHECKBOX_ON_LINK_INNER;
				else chbx = CHECKBOX_OFF_LINK_INNER;
				String newResultsText = editorPane.getText().replaceAll("\\<a"+resultID+"\\>.*\\<\\/a"+resultID+"\\>", newCheckbox);
				//		regexp:		\<a1\>.*\<\/a1\>

				//get old scroll pos:
				Rectangle aRect = editorPane.getVisibleRect();
				//substitute checkbox:
				editorPane.setText(newResultsText);		
				//scroll to new pos
				//negate rel feedback of that index:
				relevanceFeedback[resultID] = !relevanceFeedback[resultID];
				dbgRelevanceFB();												//DBG	
				//	suggestionPanel.updateUI();
				//	editorPane.scrollRectToVisible(aRect); // ?
				//editorPane.updateUI(); //causes exception :@ 
				upd();
			} else {
				String encodedInfo = e.getDescription();
				String pathToFile = verseInfoEncoder.decodeFileName(encodedInfo);
				int bookId = verseInfoEncoder.decodeBookId(encodedInfo);
				int desired = verseInfoEncoder.decodeVerseID(encodedInfo);
				int max_in_collection = verseInfoEncoder.decodeMaxInCollection(encodedInfo);
				System.out.println(">>> " + pathToFile);						//DBG
//				String contentsOfFile = resultDisplayUtility.readFromFile(pathToFile, this);
				String contentsOfFile ="<font face=\"Verdana\">" + resultDisplayUtility.getPartOfText(pathToFile, bookId, desired, max_in_collection, this, RESULTS_BEFORE, RESULTS_AFTER);
				//almost worKING		////	String contentsOfFile = resultDisplayUtility.getPartOfText(pathToFile, 2, 50, 1000, this, 20, 20); // --> ???
				//	contentsOfFile = resultDisplayUtility.parseTstmtStructure(contentsOfFile);
				//	contentsOfFile = resultDisplayUtility.decodeSpecialChars (contentsOfFile);
				//		contentsOfFile = resultDisplayUtility.transformToRTF (contentsOfFile);
				System.out.println(contentsOfFile);								//DBG
				resultsEditorPane.setText(contentsOfFile);
				tabbedPane.setSelectedComponent(resultsPanel);
				scroll(resultsEditorPane, VCENTER);
			}
		}
	}

	private void upd() {
		//editorPane.updateUI();
	}

	public void keyPressed(KeyEvent e) {
		OFFSET = 0;
		if(wantToSearch(e))
			performQuery();
	}


	private void dbgRelevanceFB() {
		//print for DBG the array: //remove when finished RFB
		System.out.print("|"); 											//DBG
		for(int i = 0 ; i < relevanceFeedback.length ; i++)
			if (relevanceFeedback[i])
				System.out.print("1|"); 								//DBG
			else System.out.print("0|"); 								//DBG
		System.out.println("");									
	}


	//other keylistener method (implemented)
	public void keyReleased(KeyEvent e) {}
	public void keyTyped(KeyEvent e) {}


	// SCROLL UTILITY ---------------------------------------------------------:
	private static final int
	NONE = 0,
	TOP = 1,
	VCENTER = 2,
	BOTTOM = 4,
	LEFT = 8,
	HCENTER = 16,
	RIGHT = 32;

	private static void scroll(JComponent c, int part){
		scroll(c, part & (LEFT|HCENTER|RIGHT), part & (TOP|VCENTER|BOTTOM));
	}

	private static void scroll(JComponent c, int horizontal, int vertical){
		Rectangle visible = c.getVisibleRect();
		Rectangle bounds = c.getBounds();
		switch (vertical){
		case TOP:     visible.y = 0; break;
		case VCENTER: visible.y = (bounds.height - visible.height) / 2; break;
		case BOTTOM:  visible.y = bounds.height - visible.height; break;
		}
		switch (horizontal){
		case LEFT:    visible.x = 0; break;
		case HCENTER: visible.x = (bounds.width - visible.width) / 2; break;
		case RIGHT:   visible.x = bounds.width - visible.width; break;
		}
		c.scrollRectToVisible(visible);
	}
	// -------------------------------------------------------------------------

}
